package com.diytomcat.http;

import java.io.InputStream;
import java.net.Socket;

import org.jsoup.internal.StringUtil;

import com.diytomcat.catalina.Context;
import com.diytomcat.catalina.Engine;
import com.diytomcat.catalina.Service;
import com.diytomcat.util.MiniBrowser;

import cn.hutool.core.util.StrUtil;

public class Request {

	private String requestString;
	private String uri;
	private Socket socket;
	private Context context;
	private Service service;

	public Request(Socket socket, Service service) throws Exception {
		this.socket = socket;
		this.service = service;
		parseHttpRequest();
		if (StringUtil.isBlank(requestString))
			return;
		parserUri();
		parserContext();
		// 修正uri 在构造方法中调用 parseContext(), 倘若当前 Context 的路径不是 "/", 那么要对 uri进行修正，
		// 比如 uri 是 /a/index.html， 获取出来的 Context路径不是 "/”， 那么要修正 uri 为 /index.html。
		if (!"/".equals(context.getPath())) {
			uri = StrUtil.removePrefix(uri, context.getPath());
			if(StrUtil.isEmpty(uri)) {
				uri = "/";
			}
		}
	}

	private void parserContext() {
		Engine engine = service.getEngine();
		context = engine.getDefaultHost().getContext(uri);
		if(null != context) 
			return;
		
		String path = StrUtil.subBetween(uri, "/", "/");
		if (null == path)
			path = "/";
		else
			path = "/" + path;

		context = service.getEngine().getDefaultHost().getContext(path);
		// 不存在取到root目录
		if (null == context)
			context = service.getEngine().getDefaultHost().getContext("/");
	}
	
	

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * @description parseHttpRequest 用于解析 http请求字符串
	 * @2020年6月8日上午10:15:49
	 * @throws Exception
	 */
	private void parseHttpRequest() throws Exception {
		InputStream is = this.socket.getInputStream();
		byte[] readBytes = MiniBrowser.readBytes(is);
		requestString = new String(readBytes, "utf-8");
	}

	/**
	 * @description parserUri解析uri
	 * @2020年6月8日上午10:16:23
	 */
	private void parserUri() {
		String temp;
		temp = StrUtil.subBetween(requestString, " ", " ");
		if (!temp.contains("?")) {
			uri = temp;
			return;
		}
		uri = StrUtil.subBefore(temp, "?", false);
	}

	public String getUri() {
		return uri;
	}

	public String getRequestString() {
		return requestString;
	}
}
